package com.todod.base.framework.common.util.office;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;

public class FileToBase64 {
    /**
     * #description 文件转Base64
     * @param filePath
     * @return
     */
    public static String fileToBase64(String filePath) {
        String base64String = "";
        File file = new File(filePath);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fileInputStream.read(bytes);
            base64String = Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64String;
    }

    public static void convertBytesToImage(byte[] imageBytes, String fileName) {
        try {
            // 创建一个字节数组输入流
            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            // 通过ImageIO读取图片
            BufferedImage image = ImageIO.read(bis);
            bis.close();

            // 确保图片不为空
            if (image != null) {
                // 将BufferedImage保存为文件
                File outputFile = new File(fileName);
                ImageIO.write(image, "png", outputFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}